package com.k.camera2

import android.graphics.SurfaceTexture
import android.hardware.Camera
import android.util.Log
import android.view.TextureView
import java.io.IOException

class PreviewCamera {
    private val TAG = "PreviewCamera"
    private var mCamera: Camera? = null
    private var mirror = false // 镜像（左右翻转）
    private var rotate = -1 // 旋转（相机传感器方向相对于设备自然方向的角度）
    private var zoom = -1 // 焦距（有些摄像头可能不支持）

    /**
     * 是否镜像
     */
    fun setMirror(mirror: Boolean) {
        this.mirror = mirror
    }

    /**
     * 旋转
     */
    fun setRotate(rotate: Int) {
        this.rotate = rotate
    }

    /**
     * 焦距
     */
    fun setZoom(zoom: Int) {
        this.zoom = zoom
    }

    /**
     * 启动相机
     */
    fun startCamera(
        textureView: TextureView,
        cameraIndex: Int,
        width: Int,
        height: Int,
        callback: ICallback
    ) {
        stopCamera()
        try {
            mCamera = Camera.open(cameraIndex)

            // TODO MWB =================
            val parameters = mCamera?.parameters
            val minExposure = parameters?.minExposureCompensation ?: 0
            val maxExposure = parameters?.maxExposureCompensation ?: 0
            Log.e(TAG, "startCamera: 最小曝光:${minExposure}")
            Log.e(TAG, "startCamera: 最大曝光:${maxExposure}")

            // TODO MWB =================

            checkPreviewSize(width, height) // 只是检查是否可以设置指定的宽高
            // 设置参数（尺寸、对焦、焦距、旋转）
            val params = mCamera!!.parameters
            params.setPreviewSize(width, height) // 设置宽高

            val focusModes = params.supportedFocusModes
            if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) { // 自动对焦
                params.focusMode = Camera.Parameters.FOCUS_MODE_AUTO
            }

            if (zoom >= 0 && params.isZoomSupported && zoom <= params.maxZoom) { // 焦点模式缩放
                params.zoom = zoom
                mCamera!!.parameters = params
            }
            mCamera!!.parameters = params // 设置相机的模式

            if (rotate >= 0) { // 相机画面旋转角度
                mCamera!!.setDisplayOrientation(rotate)
            }
            // 预览初始化（左右翻转）
            initPreview(textureView)

            if (mirror) {
                textureView.rotationY = 180f
            }
            // 回调
            mCamera!!.setPreviewCallback { data, camera ->
                callback.onData(data, camera)
            }
            callback.onSucc(mCamera!!)
        } catch (e: Exception) {
            e.printStackTrace()
            callback.onError(e)
        }
    }

    /**
     * 关闭相机
     */
    fun stopCamera() {
        try {
            mCamera?.setPreviewCallback(null)
            mCamera?.stopPreview()
            mCamera?.release()
            mCamera = null
        } catch (e: Exception) {
        }
    }

    /**
     * 检查预览尺寸
     */
    private fun checkPreviewSize(width: Int, height: Int) {
        var sizeOk = false
        val sizeList = mCamera!!.parameters.supportedPreviewSizes
        for (size in sizeList) {
            if (size.width == width && size.height == height) {
                sizeOk = true
            }
        }
        if (!sizeOk) {
            throw Exception("不支持该预览尺寸: [$width,$height]")
        }
    }

    private fun initPreview(textureView: TextureView) {
        textureView.surfaceTextureListener = object : TextureView.SurfaceTextureListener {
            override fun onSurfaceTextureAvailable(
                surfaceTexture: SurfaceTexture,
                i: Int,
                i1: Int
            ) {
                try {
                    mCamera?.setPreviewTexture(surfaceTexture)
                    mCamera?.startPreview()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }

            override fun onSurfaceTextureSizeChanged(
                surfaceTexture: SurfaceTexture,
                i: Int,
                i1: Int
            ) {
            }

            override fun onSurfaceTextureDestroyed(surfaceTexture: SurfaceTexture): Boolean {
                stopCamera()
                return false
            }

            override fun onSurfaceTextureUpdated(surfaceTexture: SurfaceTexture) {
            }
        }
    }

    /**
     * TODO MWB 设置曝光
     */
    private fun setExposure(exposureValue: Int) {
        val parameters = mCamera?.parameters
        parameters?.exposureCompensation = exposureValue
        mCamera?.parameters = parameters
    }

    interface ICallback {
        fun onSucc(camera: Camera)
        fun onData(data: ByteArray, camera: Camera)
        fun onError(e: Exception)
    }
}
